#!/usr/bin/env python

import sys
import os
import inspect
import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
from py_compile import compile
compile(os.path.split(__file__)[0]+"/"+"form_callbacks.py")
import form_callbacks as callbacks


class holder:
	def __init__(self, cn, tree):
		self.cn = cn
		self.wTree = tree
	def get_lambda(self):
		return lambda cw, cd="": self.calls(self.cn, cw, cd)
	def calls(self, callname, callwidget, calldata=''):
		func = dir(callbacks)
		i=func.index(callname)
		obj = getattr(callbacks, func[i])
		obj(callwidget, calldata, self.wTree)


def get_callback_functions(handarray):
	working_directory=os.path.split(__file__)[0]+"/"
	sys.path.insert(0, working_directory)
	call_file_name = working_directory+"form_callbacks.py"
	callbacksmod = __import__(inspect.getmodulename(call_file_name))
	a=""
	funcs = dir(callbacksmod)
	for c in handarray:
		if c in funcs: continue
		else: a+="\ndef "+c+"(widget, data, wtree):\n\tprint \"function '"+c+"' not implmented\"\n\tpass\n"
	return a
#


gladefilepath = None
def get_handlers():
	global gladefilepath
	gladefile = open(gladefilepath,"r")
	handlerlines = []
	handlers = {}
	for line in gladefile.readlines():
		line = line.strip()
		if line[0:7] == '<signal':
			handlerlines.append(line)
	for item in handlerlines:
		if item.find('handler=') >= 0:
			tail = item[item.find('handler=') +9:]
			handlers[tail[:tail.find('\"')]] = 0
	return handlers.keys()
#
class Form:
	def __init__(self):
		global gladefilepath
		self.gladefile = os.path.split(__file__)[0]+'/form.glade'
		gladefilepath = self.gladefile
		self.checkcallbacks()
		self.wTree = gtk.glade.XML(self.gladefile)
		callbacks.init(self.wTree)
		self.handarray = get_handlers()
		self.wTree.signal_autoconnect(self.get_dictionary())
	def calls(self, callname, callwidget, calldata=''):
		func = dir(callbacks)
		i=func.index(callname)
		obj = getattr(callbacks, func[i])
		obj(callwidget, calldata, self.wTree)
	def checkcallbacks(self):
		global callbacks
		newcalls = get_callback_functions(get_handlers())
		if newcalls != "":
				self.callbacks_file= open(os.path.split(__file__)[0]+"/"+"form_callbacks.py","a")
				self.callbacks_file.write(newcalls)
				self.callbacks_file.close()
				compile(os.path.split(__file__)[0]+"/"+"form_callbacks.py")
				reload(callbacks)
	def get_dictionary(self):
		indent = "\t"
		dic = {}
		for hand in self.handarray:
			s = holder(hand, self.wTree)
			dic[hand] = s.get_lambda()
		return dic
#

if __name__ == '__main__':
	someclass = Form()
	try:
		gtk.main()
    someclass.show();
	except KeyboardInterrupt:
		sys.exit(1)
#



